﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace machine_registration.Services
{

    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Threading;
    using System.Threading.Tasks;
    using EnterpriseWeChatInform;
    using machine_registration.Helpers;
    using machine_registration.Infrastructure;
    using machine_registration.Models;

    public class TimeAlertManager: IData_SourceService,IDisposable
    {
        // 存储用户添加的 Information_Push 对象
        private  ObservableCollection<Information_Push> _alertItems;

        // 用于取消定时任务的Token
        private CancellationTokenSource _cancellationTokenSource;

        // 事件：当到达指定时间时触发
        public event Action<Information_Push> OnAlertTimeReached;

        /// <summary>
        /// 设置数据源
        /// </summary>
        /// <param name="alertItems"></param>
        public void SetAlertItems(ObservableCollection<Information_Push> alertItems)
        {
            _alertItems = alertItems;
        }
        /// <summary>
        /// 初始化数据
        /// </summary>
        public void Initialize()
        {
            //启动后开启消息推送
            _alertItems=JsonFileHelper.LoadFromJson<Information_Push>("data.json");

            //把_alertItems 字段设置为false
            foreach (var item in _alertItems)
            {
                item.Isok = false;
            }
        }
        public void RemoveAlertItems(params Information_Push[] items)
        {
            if (_alertItems == null )
            {
               throw new ArgumentNullException("请先设置数据源");
            }
            foreach (var item in items)
            {
                _alertItems.Remove(item);
            }
        }
        public ObservableCollection<Information_Push> GetInformation()
        {
            if (_alertItems == null)
            {
                throw new ArgumentNullException("请先设置数据源");
            }
            return _alertItems;
        }
        /// <summary>
        /// 添加一个或多个 Information_Push 对象
        /// </summary>
        /// <param name="items">要添加的 Information_Push 对象</param>
        public void AddAlertItems(params Information_Push[] items)
        {
            if (_alertItems == null)
            {
                throw new ArgumentNullException("请先设置数据源");
            }
            foreach (var item in items)
            {
                if (item.Time >= TimeSpan.Zero && item.Time < TimeSpan.FromDays(1))
                {
                    _alertItems.Add(item);
                }
                else
                {
                    throw new ArgumentException("时间点必须在00:00:00到23:59:59之间。");
                }
            }
        }

        /// <summary>
        /// 启动定时任务，检查是否到达指定时间
        /// </summary>
        public void Start()
        {
            if (_alertItems == null)
            {
                throw new ArgumentNullException("请先设置数据源");
            }
            _cancellationTokenSource = new CancellationTokenSource();
            Task.Run(() => CheckAlertTimesAsync(_cancellationTokenSource.Token));
        }

        /// <summary>
        /// 停止定时任务
        /// </summary>
        public void Stop()
        {
            _cancellationTokenSource?.Cancel();
        }

        /// <summary>
        /// 异步检查是否到达指定时间
        /// </summary>
        private async Task CheckAlertTimesAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                var currentTime = DateTime.Now.TimeOfDay;
                // 创建仅包含时分秒的新TimeSpan
                var currentTimeTruncated = new TimeSpan(currentTime.Hours,
                                                      currentTime.Minutes,
                                                      currentTime.Seconds);

                foreach (var item in _alertItems)
                {
                    // 确保对比双方都使用精确到秒的时间格式
                    var itemTimeTruncated = new TimeSpan(item.Time.Hours,
                                                       item.Time.Minutes,
                                                       item.Time.Seconds);

                    if (currentTimeTruncated == itemTimeTruncated
                        && !item.Isok
                        && !string.IsNullOrEmpty(item.Enterprise_wechat_address))
                    {
                        OnAlertTimeReached?.Invoke(item);
                        PushMessage(item);
                        item.Isok = true;
                    }
                }

                // 每隔1秒检查一次
                await Task.Delay(1000, cancellationToken);
            }
        }

        //消息推送
        public async void PushMessage(Information_Push e)
        {
            Debug.WriteLine($"{e.ID} : {e.Time} 已提醒:{e.Message}");
            //推送地址
            string url = e.Enterprise_wechat_address;
            string content = $"{e.Message}";
            try
            {
                //   https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6072ed81-7294-48b5-a017-fc990e2ff40e
                // 初始化通知器
                using var notifier = new WeChatNotifier(e.Enterprise_wechat_address, "设备管理系统");


                // 发送 Markdown 消息
                await notifier.SendAsync(new WeChatMessage(
                    WeChatMessageType.Text,
                    $" {e.Type} \n {e.Time}  时间已到  \n {e.Message}"
                ));
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"{e.ID} : {e.Time} 推送失败:{e.Message}");
            }
        }



        public void Dispose()
        {
            //注销资源
            _alertItems=null; 
            _cancellationTokenSource?.Dispose();
            _cancellationTokenSource = null;
        }

    }
}
